package com.yand.disk.demo.utils;


import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.UUID;

/**
 * 网盘工具类
 */
public class NetDiskUtils {

    /**
     * 创建link 的code
     *   md5 与 base64 算法
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String createLinkCode() throws NoSuchAlgorithmException {
     String message = System.nanoTime()+(new Random().nextInt(90)+10)+"";
     MessageDigest  md = MessageDigest.getInstance("MD5");
     byte [] md5 =  md.digest(md.digest(message.getBytes()));
     BASE64Encoder encoder = new BASE64Encoder();
     String codeStr = encoder.encode(md5);
     codeStr = codeStr.replaceAll("=",new Random().nextInt(9)+"")
                      .replaceAll("/","_")
                      .replaceAll("\\+","q");


     return codeStr;
    }


    /**
     * 创建下载token值，一次一token
     *  直接通过md5 摘要算法生成
     * @return
     */
    public static String createAccessToken(){

        byte[] digest = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");

            digest  = md5.digest(UUID.randomUUID().toString().getBytes("utf-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //16是表示转换为16进制数
        String md5Str = new BigInteger(1, digest).toString(16);
        return md5Str;
    }

    /**
     * 创建提取码方法
     * @return
     */
    public static int createValiCode(){
      return   new Random().nextInt(8999)+1000;
    }

    /**
     * 获取当前服务的ip 与 端口 返回  ip:port 形式字符串
     * @return
     */
    public static String getIpAndPort(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        return request.getServerName()+":"+request.getServerPort();
    }







}
